<template>
  <main class="container text-white">
    <div class="pt-4 mb-8 relative">
      <input
        type="text"
        placeholder="请输入城市名称"
        class="py-2 px-1 w-full bg-transparent border-b focus:border-weather-secondary focus:outline-none focus:shadow-md"
        v-model="cityNameValue"
        @input="handleInput"
      />
      <ul
        class="absolute bg-weather-secondary text-white w-full shadow-md py-2 px-1 top-[62px]"
        :style="{ display: isDropdownVisible ? '' : 'none' }"
      >
        <p v-if="errorMessage">{{ errorMessage }}</p>
        <li
          v-else
          v-for="city in inputGeocodes"
          :key="city.adcode"
          class="cursor-pointer"
          @click="handleRouterChange(city.name, city.adcode)"
        >
          {{ city.name }}
        </li>
      </ul>
    </div>
    <h2 class="text-center duration-200" v-if="cityList.length === 0">
      暂时没有保存过城市天气信息，请查询后点击右上角"+"号保存。
    </h2>
    <div class="mt-10 max-h-[300px]" :style="{ display: isDropdownVisible ? 'none' : '' }" v-else>
      <div
        class="flex justify-between"
        v-for="item in cityList"
        :key="item.adcode"
        @mouseover="item.isHover = true"
        @mouseout="item.isHover = false"
      >
        <div
          class="mb-4 bg-weather-secondary py-2 px-4 flex justify-between cursor-pointer w-full duration-300"
          :class="{ 'w-4/5': item.isHover }"
        >
          <h3>{{ item.city }}</h3>
          <span>{{ getTemByAdcode(item.adcode) }}°C</span>
        </div>
        <div class="flex mb-4 gap-2" :style="{ display: item.isHover ? 'flex' : 'none' }">
          <button
            class="bg-yellow-500 text-center w-[80px]"
            @click="handleRouterChange(item.city, item.adcode)"
          >
            查看
          </button>
          <button class="bg-yellow-500 text-center w-[80px]" @click="removeCity(item.adcode)">
            删除
          </button>
        </div>
      </div>
    </div>
    <h2 class="mt-6" v-if="locationAllWeather.length > 0 && locationWeather">近期天气</h2>
    <weather-chart
      v-if="locationAllWeather.length > 0 && locationWeather"
      :forecasthWeatherData="locationAllWeather"
    />
    <h1 class="text-center text-white text-lg" v-else>天气信息加载中...</h1>
  </main>
</template>

<script setup>
import { storeToRefs } from 'pinia'
import { onMounted, ref, watch,computed } from 'vue'
import { useRouter } from 'vue-router'
import { useMaskStore } from '../stores/maskControl.js'
import { localStorageStore } from '../stores/localStroge.js'
const { toggleMask } = useMaskStore()
const {
  cityName,
  cityAdcode,
  inputGeocodes,
  errorMessage,
  cityList,
  locationAllWeather,
  locationWeather,
  cityTemp
} = storeToRefs(localStorageStore())
const { searchCityHomeview, handleRouterChange, removeCity, getAllWeatherByIP, tempFunc } =
  localStorageStore()

import weatherChart from '@/components/weatherChart.vue'
// 定义鼠标是否悬停
// const isHover = ref(false)

// 定义数据
// input获得数据集
// const inputGeocodes = ref([])
// 城市adcode
// const cityAdcode = ref('')
// 错误信息
// const errorMessage = ref('')
// 显示子组件

// input输入框值
const cityNameValue = ref('')
// 控制下拉框是否显示
const isDropdownVisible = ref(false)

//防抖函数,通过设定时间间隔来防止频繁的请求,如input输入框输入内容
function debounce(func, wait) {
  let timeout
  return function () {
    const context = this
    const args = arguments
    clearTimeout(timeout)
    timeout = setTimeout(() => {
      func.apply(context, args)
    }, wait)
  }
}
const handleInput = debounce(function () {
  searchCityHomeview(cityNameValue.value)
  console.log('城市名称', cityNameValue.value)
}, 500)

const getTemByAdcode = computed(() => {
  return (adcode) => {
    const found = cityTemp.value.find(item => item.adcode === adcode);
    return found ? found.tem : null; // 如果未找到，返回 null
  };
});

watch(cityNameValue, (newValue) => {
  if (newValue.trim() === '') {
    isDropdownVisible.value = false
    return
  }
  isDropdownVisible.value = true
  console.log('城市名称', newValue)
})

onMounted(() => {
  if (localStorage.getItem('cityList')) {
    cityList.value = JSON.parse(localStorage.getItem('cityList'))
    tempFunc(cityList)
    console.log('城市温度', cityTemp.value)
  }
  getAllWeatherByIP()
})
</script>

<style scoped>
.container {
  width: 100%;
  margin-right: auto;
  margin-left: auto;
  padding-right: 10rem;
  padding-left: 10rem;
}
</style>
